package com.hdu.h_health.Adapter;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.hdu.h_health.R;
import com.hdu.h_health.utils.ViewUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import cn.bmob.newim.bean.BmobIMConversation;
import cn.bmob.newim.bean.BmobIMMessage;
import cn.bmob.newim.bean.BmobIMMessageType;
import cn.bmob.newim.bean.BmobIMSendStatus;
import cn.bmob.newim.bean.BmobIMUserInfo;
import cn.bmob.v3.BmobUser;

/**
 * 会话列表适配器
 * Created by 612 on 2016/3/9.
 */
public class ChatAdapter extends BaseAdapter {

    //文本
    private final int TYPE_RECEIVER_TXT = 0;
    private final int TYPE_SEND_TXT = 1;
    //图片
    private final int TYPE_SEND_IMAGE = 2;
    private final int TYPE_RECEIVER_IMAGE = 3;
    //位置
    private final int TYPE_SEND_LOCATION = 4;
    private final int TYPE_RECEIVER_LOCATION = 5;
    //语音
    private final int TYPE_SEND_VOICE = 6;
    private final int TYPE_RECEIVER_VOICE = 7;

    //列表项种类
    private final int TYPE_COUNT = 2;

    /**
     * 显示时间间隔:10分钟
     */
    private final long TIME_INTERVAL = 10 * 60 * 1000;

    private List<BmobIMMessage> msgs = new ArrayList<>();

    private String currentUid = "";
    private BmobIMConversation c;

    private LayoutInflater inflater;

    public ChatAdapter(Context context, BmobIMConversation c) {
        try {
            //获取当前用户的ID
            currentUid = BmobUser.getCurrentUser(context).getObjectId();
        } catch (Exception e) {
            e.printStackTrace();
        }
        this.c = c;
        inflater = LayoutInflater.from(context);
    }

    public void setDatas(List<BmobIMMessage> messages) {
        msgs.clear();
        if (null != messages) {
            msgs.addAll(messages);
        }
    }

    public void addMessages(List<BmobIMMessage> messages) {
        msgs.addAll(0, messages);
    }

    public void addMessage(BmobIMMessage message) {
        msgs.addAll(Arrays.asList(message));
    }

    /**
     * 获取消息
     */
    public BmobIMMessage getIMItem(int position) {
        return msgs.get(position);
    }

    /**
     * 移除消息
     */
    public void remove(int position) {
        msgs.remove(position);
        notifyDataSetChanged();
    }

    public BmobIMMessage getFirstMessage() {
        if (msgs != null && msgs.size() > 0) {
            return msgs.get(0);
        } else {
            return null;
        }
    }

    /**
     * 根据两条消息的时间间隔来决定是否显示时间
     */
    private boolean shouldShowTime(int position) {
        if (position == 0) {
            return true;
        }
        long lastTime = msgs.get(position - 1).getCreateTime();
        long curTime = msgs.get(position).getCreateTime();
        return curTime - lastTime > TIME_INTERVAL;
    }


    @Override
    public int getCount() {
        return msgs.size();
    }

    @Override
    public Object getItem(int position) {
        return msgs.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getItemViewType(int position) {
        BmobIMMessage message = msgs.get(position);
        if (message.getMsgType().equals(BmobIMMessageType.IMAGE.getType())) {
            return message.getFromId().equals(currentUid) ? TYPE_SEND_IMAGE : TYPE_RECEIVER_IMAGE;
        } else if (message.getMsgType().equals(BmobIMMessageType.LOCATION.getType())) {
            return message.getFromId().equals(currentUid) ? TYPE_SEND_LOCATION : TYPE_RECEIVER_LOCATION;
        } else if (message.getMsgType().equals(BmobIMMessageType.VOICE.getType())) {
            return message.getFromId().equals(currentUid) ? TYPE_SEND_VOICE : TYPE_RECEIVER_VOICE;
        } else {
            return message.getFromId().equals(currentUid) ? TYPE_SEND_TXT : TYPE_RECEIVER_TXT;
        }
    }

    @Override
    public int getViewTypeCount() {
        return TYPE_COUNT;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        BmobIMMessage bmobIMMessage = msgs.get(position);
        View view;
        switch (getItemViewType(position)) {
            case 0://接收的文本
                view = handleReceiveText(position, convertView, parent, bmobIMMessage);
                break;
            case 1://发送的文本
                view = handleSendText(position, convertView, parent, bmobIMMessage);
                break;
            default:
                view = null;
                Log.i("Main", "chatAdapter getView() null");
                break;
        }
        return view;
    }

    private View handleSendText(int position, View convertView, ViewGroup parent, BmobIMMessage bmobIMMessage) {
        SendTextViewHolder sv;
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.item_chat_sent_message, parent, false);
            sv = new SendTextViewHolder();
            sv.tv_time = (TextView) convertView.findViewById(R.id.tv_time);
            sv.tv_message = (TextView) convertView.findViewById(R.id.tv_message);
            sv.tv_send_status = (TextView) convertView.findViewById(R.id.tv_send_status);
            sv.iv_avatar = (ImageView) convertView.findViewById(R.id.iv_avatar);
            sv.iv_fail_resend = (ImageView) convertView.findViewById(R.id.iv_fail_resend);
            sv.progress_load = (ProgressBar) convertView.findViewById(R.id.progress_load);
            convertView.setTag(sv);
        } else {
            sv = (SendTextViewHolder) convertView.getTag();
        }
        if (shouldShowTime(position)) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            sv.tv_time.setText(dateFormat.format(bmobIMMessage.getCreateTime()));
        } else {
            sv.tv_time.setVisibility(View.GONE);
        }
        sv.tv_message.setText(bmobIMMessage.getContent());
        sv.tv_send_status.setText(bmobIMMessage.getSendStatus() + "");

        //设置发送消息用户的头像
        final BmobIMUserInfo info = bmobIMMessage.getBmobIMUserInfo();
        ViewUtils.setPic(info != null ? info.getAvatar() : null, R.mipmap.head, sv.iv_avatar);

        int status = bmobIMMessage.getSendStatus();
        if (status == BmobIMSendStatus.SENDFAILED.getStatus()) {
            sv.iv_fail_resend.setVisibility(View.VISIBLE);
            sv.progress_load.setVisibility(View.GONE);
        } else if (status == BmobIMSendStatus.SENDING.getStatus()) {
            sv.iv_fail_resend.setVisibility(View.GONE);
            sv.progress_load.setVisibility(View.VISIBLE);
        } else {
            sv.iv_fail_resend.setVisibility(View.GONE);
            sv.progress_load.setVisibility(View.GONE);
        }
        return convertView;
    }

    private View handleReceiveText(int position, View convertView, ViewGroup parent, BmobIMMessage bmobIMMessage) {
        ReceiveTextViewHolder rv;
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.item_chat_received_message, parent, false);
            rv = new ReceiveTextViewHolder();
            rv.tv_message = (TextView) convertView.findViewById(R.id.tv_message);
            rv.tv_time = (TextView) convertView.findViewById(R.id.tv_time);
            rv.iv_avatar = (ImageView) convertView.findViewById(R.id.iv_avatar);
            convertView.setTag(rv);
        } else {
            rv = (ReceiveTextViewHolder) convertView.getTag();
        }
        if (shouldShowTime(position)) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
            String time = dateFormat.format(bmobIMMessage.getCreateTime());
            rv.tv_time.setText(time);
        } else {
            rv.tv_time.setVisibility(View.GONE);
        }
        //设置接收消息用户的头像
        final BmobIMUserInfo info = bmobIMMessage.getBmobIMUserInfo();
        ViewUtils.setPic(info != null ? info.getAvatar() : null, R.mipmap.head, rv.iv_avatar);
        String content = bmobIMMessage.getContent();
        rv.tv_message.setText(content);
        return convertView;
    }
}
